<?php

namespace Addons\OaSystem\Controller;
use Think\ManageBaseController;

class OaUserCenterController extends OaBaseController
{
    var $model;

    function _initialize()
    {
//        $menus = D ( 'Common/Menu' )->get ();
//
//        $this->assign ( $menus );
        parent::_initialize();
//        $action = strtolower(ACTION_NAME);
//        $res ['title'] = '个人中心';
//        $res ['url'] = addons_url('OaSystem://OaUserCenter/personalinfo', array('mdm' => I('mdm')));
//        $res ['class'] = $action == 'personalinfo' ? 'cur' : '';
//        $nav [] = $res;
//        $this->assign('nav', $nav);
//
//        $res ['title'] = '个人信息';
//        $sub_nav[] = $res;
//        $res ['title'] = '日常考勤';
//        $res ['url'] = addons_url('OaSystem://OaUserCenter/dailyattendance', array('mdm' => I('mdm')));
//        $res ['class'] = $action == 'dailyattendance' ? 'cur' : '';
//        $sub_nav[] = $res;
//
//        $res ['title'] = '角色指派';
//        $res ['url'] = addons_url('OaSystem://OaUserCenter/assignRoleTree', array('mdm' => I('mdm')));
//        $res ['class'] = $action == 'assignroletree' ? 'cur' : '';
//        $sub_nav[] = $res;
//
////        $res ['title'] = '请假申请';
////        $sub_nav[] = $res;
////        $res ['title'] = '加班申请';
////        $res ['url'] = addons_url('OaSystem://OaUserCenter/overworklists', array('mdm' => I('mdm')));
////        $res ['class'] = $action == 'overworklists' ? 'cur' : '';
////        $sub_nav[] = $res;
////        $res ['title'] = '我待办事项';
////        $res ['url'] = addons_url('OaSystem://OaUserCenter/myworks', array('mdm' => I('mdm')));
////        $res ['class'] = $action == 'myworks' ? 'cur' : '';
////        $sub_nav[] = $res;
//
//        $this->assign('sub_nav', $sub_nav);
    }

    public function personalinfo() {

        $data = db_select('oa_employee', ['id'=>$this->cur_emp_id]);
        foreach ($data as $i => $v) {
            $dept = M('oa_dept')->where('id=%d',$v['dept_id'])->find();
            $duty = M('oa_duty')->where('id=%d',$v['duty_id'])->find();
            $adminLvl = M('oa_emp_admin_level')->where('id=%d',$v['adminLvl_id'])->find();

            $data[$i]['dept'] = $dept['name'];
            $data[$i]['duty'] = end(explode('_', $duty['name']));
            $data[$i]['adminLvl'] = $adminLvl['name'];
            $data[$i]['mobile'] = implode(', ', json_decode($v['mobile_list'],true));
        }
        $this->assign('empinfo', $data);
        $this->display();
    }

    function dailyattendance()
    {
        if(IS_POST) {
            $querypara = json_encode($_POST);
            redirect(U('lists', array('query'=>$querypara)));
        }

        $p = empty(I('p')) ? 1 : I('p');
        $row = 20;
        $querypara = json_decode($_GET['query'], true);
        if(empty($querypara)) {
            $y_start = $y_end = date('Y');
            $m_end = date('m');
            $m_start = $m_end - 1;
        } else {
            $y_start = $querypara['year_start'];
            $y_end = $querypara['year_end'];
            $m_start = $querypara['month_start'];
            $m_end = $querypara['month_end'];
        }

        $query_start = strtotime($y_start.'-'.$m_start.'-01 00:00:00');
        $m_days = cal_days_in_month(CAL_GREGORIAN, $m_end, $y_end);
        $query_end = strtotime($y_end.'-'.$m_end.'-'.$m_days.' 23:59:59');
        $now = time();
        if($query_end > $now) $query_end = $now;
        $len = (int)(($query_end - $query_start)/86400) + 1;
        $query_start += ($p-1)*$row*86400;
        $tmp_end = $query_start + $row*86400 - 1;
        $query_end = ($query_end > $tmp_end) ? $tmp_end : $query_end;

        $emp_id = $this->cur_emp_id;
        $empInfo = $this->getCurUserInfo();

        $attendances = $this->getAttendances($query_start, $query_end, $emp_id);
        for($t=$query_start, $i=0; $t < $query_end; $t+=86400,$i++) {
            $data[$i]['name'] = $empInfo['name'];
            $data[$i]['dept'] = $empInfo['dept'];
            $data[$i]['date'] = date('Y-m-d', $t);
            $data[$i]['day_type'] = $this->getDayType($t);
            $data[$i]['punchtime'] = $attendances[$t]['time'];
            $data[$i]['leave_hours'] = $this->getLeaveTime($t,$emp_id);
            if(!empty($data[$i]['leave_hours']))
                $data[$i]['remark'] = '休假';
        }

        for($y = 2018; $y <= 2030; $y++) {
            $query['date']['ystart'][$y]['id'] = $y;
            $query['date']['ystart'][$y]['name'] = $y;
            $query['date']['yend'][$y]['id'] = $y;
            $query['date']['yend'][$y]['name'] = $y;
        }
        for($m = 1; $m <= 12; $m++) {
            $query['date']['mstart'][$m]['id'] = $m;
            $query['date']['mstart'][$m]['name'] = $m;
            $query['date']['mend'][$m]['id'] = $m;
            $query['date']['mend'][$m]['name'] = $m;
        }
        $query['date']['ystart'][$y_start]['selected'] = 'selected';
        $query['date']['yend'][$y_end]['selected'] = 'selected';
        $query['date']['mstart'][$m_start]['selected'] = 'selected';
        $query['date']['mend'][$m_end]['selected'] = 'selected';

        if ($len > $row) {
            $page = new \Think\Page ( $len, $row );
            $page->setConfig ( 'theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%' );
            $list_data['_page'] = $page->show ();
        }
        $this->assign('_page',$list_data['_page']);
        $this->assign('list_data', $data);
        $this->assign('query', $query);
        $this->display();
    }

    private function getAttendances($date_start, $date_end, $emp_id) {
        $map['emp_id'] = $emp_id;
        $map['date'] = array(array('egt', $date_start), array('elt', $date_end));
        $attendances = db_select('oa_emp_attendance', $map, 'date asc');
        $attLists = array();
        foreach ($attendances as $a) {
            $empInfo = $this->getUserInfo($a['emp_id']);
            $attLists[$a['date']]['name'] = $empInfo['name'];
            $attLists[$a['date']]['dept'] = $empInfo['dept'];
            $attLists[$a['date']]['date'] = date('Y-m-d', $a['date']);
            $time = ($a['type']%2==1 && !empty($a['time2nd'])) ? $a['time2nd'] : $a['time'];
            $attLists[$a['date']]['time'][$a['type']] = date('H:i', $time);
        }
        return $attLists;
    }

    private function getDayType($dayTs) {
        $holidays = $this->workTime['holidays'];
        $adjust_rest_days = $this->workTime['restdays'];
        $adjust_work_days = $this->workTime['workdays'];
        if(in_array($dayTs, $holidays))
            return '节假日';
        if(in_array($dayTs, $adjust_rest_days))
            return '休息日';
        if(in_array($dayTs, $adjust_work_days))
            return '工作日';
        $dayofweek = date('w', $dayTs);
        if($dayofweek >= 1 && $dayofweek <= 5)
            return '工作日';
        else
            return '休息日';
    }

    private function getLeaveTime($dayTs, $emp_id) {
        $clock_on = $this->workTime['clockon'];
        $work_hour = $dayTs + $clock_on[0];
        $off_hour = $dayTs + end($clock_on);

        $map['applyer'] = $emp_id;
        $map['type'] = 2;
        $map['is_del'] = 0;
        $map['status'] = 1;
        $map['start_time'] = array(array('egt', $work_hour), array('elt', $off_hour));
        if(($leaveApply = db_select('oa_application', $map)) == NULL) {
            unset($map['start_time']);
            $map['end_time'] = array(array('egt', $work_hour), array('elt', $off_hour));
            if(($leaveApply = db_select('oa_application', $map)) == NULL)
                return null;
        }
        $leave_des = null;
        foreach ($leaveApply as $la) {
            $leave_start = ($la['start_time'] > $work_hour) ? $la['start_time'] : $work_hour;
            $leave_end = ($la['end_time'] > $off_hour) ? $off_hour : $la['end_time'];
            $leave_des .= date('H:i', $leave_start).' - '.date('H:i', $leave_end).'<br>';
        }
        return $leave_des;
    }

    function assignRoleTree() {
        $depts = D("OaDeptView")->order('grade_value')->select();
        $tree = array();
        foreach ($depts as $dept) {
            if(empty($dept['pid'])) {
                $tree[$dept['id']] = $this->buildTreeNode($dept);
            }
            else {
                $this->buildMemberTree($tree, $dept);
            }
        }
        $cur_user_dept = $this->getCurUserInfo()['dept'];
        $deptNode[0] = $this->findDeptNode($tree, $cur_user_dept);
        $memberTreeHtmlStr = $this->buildMemberTreeHtml($deptNode);
        $this->assign('membershipTree', $memberTreeHtmlStr);
        $this->display('depttree');
    }

    function userRolelists(){
        $emp_id = $_GET['emp_id'];

        $res['title'] = '指派';
        $res['is_buttion'] = false;
        $res['url'] = addons_url ( 'OaSystem://OaUserCenter/assignRole' ,array('mdm'=>I('mdm'), 'emp_id'=>$emp_id));
        $top_more_button[] = $res;
        $res['title'] = '部门显示';
        $res['is_buttion'] = false;
        $res ['url'] = addons_url ( 'OaSystem://OaUserCenter/assignRoleTree' ,array('mdm'=>I('mdm')));
        $top_more_button[] =$res;

        $this->assign('top_more_button',$top_more_button);
        $this->assign('add_button',true);

        //解析列表规则
        $model = $this->getModel('oa_user_role');
        $list_data = $this->_get_model_list($model);
        $grids = $list_data['list_grids'];
        $data = $list_data['list_data'];

        foreach ($data as $i => $v) {
            $user = db_find('oa_employee', ['id'=>$v['emp_id']]);
            $dept = db_find('oa_dept', ['id'=>$user['dept_id']]);
            $role = db_find('oa_role', ['id'=>$v['role_id']]);
            $user_assign = db_find('oa_employee', ['id'=>$v['assigned_by']]);

            $data[$i]['emp_id'] = $user['name'].' ['.$dept['name'].']';
            $data[$i]['role_id'] = $role['name'];
            $data[$i]['assigned_by'] = $user_assign['name'];
        }
        if(empty($data)) {
            $user = db_find('oa_employee', ['id'=>$emp_id]);
            $data[0]['emp_id'] = $user['name'];
        }
        $this->assign( 'list_grids', $grids);
        $this->assign('list_data',  $data);
        $this->display('lists');
    }

    function assignRole() {
        if(IS_POST) {
            $data['appid'] = $this->appId;
            $data['emp_id'] = $_POST['emp_id'];
            $role = db_select('oa_role');
            foreach($role as $vo) {
                if($_POST[$vo['name']] == 1) {
                    $data['role_id'] = $vo['id'];
                    if(!db_find('oa_user_role', $data)) {
                        $user = db_find('oa_employee', ['userid'=>$this->mid]);
                        $data['assigned_by'] = empty($user) ? 0 : $user['id'];
                        M('oa_user_role')->add($data);
                    }
                }
            }
            $this->success('指派成功！', U ( 'userRolelists', array('emp_id'=>$data['emp_id'])), 600);
        } else {
            $emp_id = $_GET['emp_id'];
            $employee = db_find('oa_employee', ['id'=>$emp_id]);
            $curUserRoles = db_select('oa_user_role', ['emp_id'=>$this->cur_emp_id]);
            foreach ($curUserRoles as $i => $v) {
                $role = db_find('oa_role', ['id'=>$v['role_id']]);
                $roles[$i]['id'] = $role['id'];
                $roles[$i]['name'] = $role['name'];
            }

            $this->assign('emp', $employee);
            $this->assign('roles', $roles);
            $this->display('assignrole');
        }
    }


    private function findDeptNode($root, $dept_name) {
        foreach ($root as $i => $n) {
            if($n['name'] == $dept_name)
                return $root[$i];
        }

        foreach ($root as $i => $n) {
            if(!empty($n['subDept'])) {
                $node = $this->findDeptNode($n['subDept'], $dept_name);
                if(!empty($node))
                    return $node;
            }
        }
        return false;
    }

    private function buildTreeNode($dept) {
        $members = db_select('oa_employee', ['dept_id'=>$dept['id']], null, 'id,name');
        foreach ($members as $i => $member) {
            $roles = array();
            //array_push($roles, array('name'=>'角色管理->'));
            $user_roles = db_select('oa_user_role', ['emp_id'=>$member['id']]);
            foreach ($user_roles as $user_role) {
                $role = db_find('oa_role', ['id'=>$user_role['role_id']], null, 'name');
                if(!empty($user_role['assigned_by'])) {
                    $assignedBy = db_find('oa_employee', ['id'=>$user_role['assigned_by']]);
                    $role['assigned_by'] = $assignedBy['name'];
                }
                array_push($roles, $role);
            }
            $members[$i]['roles'] = $roles;
        }
        $node = array (
            'name'=>$dept['name'],
            'member'=>$members,
            'subDept'=>array(),
        );
        return $node;
    }

    private function buildMemberTree(&$tree, $dept) {
        //find father node
        foreach ($tree as $i => $node) {
            if($dept['pid'] == $i) {
                $tree[$i]['subDept'][$dept['id']] = $this->buildTreeNode($dept);
                return true;
            }
        }
        foreach ($tree as $i => $node) {
            if(!empty($node['subDept'])) {
                if($this->buildMemberTree($tree[$i]['subDept'], $dept))
                    return true;
            }
        }
        return false;
    }

    private function buildMemberTreeHtml($tree) {
        $treeHtmlStr = '';
        foreach ($tree as $node) {
            $treeHtmlStr .= '<li><span class="folder" style="font-weight:bold;color:#002b36">'.$node['name'].'</span>';
            $treeHtmlStr .= '<ul>';
            foreach ($node['member'] as $member) {
                $treeHtmlStr .= '<li><span class="folder" style="color:#0fb1da">'.'<a href="'.U('userRolelists',array('emp_id'=>$member['id'])).'">'.$member['name'].'</a></span>';
                $treeHtmlStr .= '<ul>';
                foreach ($member['roles'] as $role) {
                    if(empty($role['assigned_by']))
                        $treeHtmlStr .= '<li><span class="file" style="color:#00CC33">'.$role['name'].'</span>';
                    else
                        $treeHtmlStr .= '<li><span class="file" style="color:#00CC33">'.$role['name'].' <-'.$role['assigned_by'].'</span>';
                }
                $treeHtmlStr .= '</ul></li>';
            }
            if(!empty($node['subDept'])) {
                $treeHtmlStr .= $this->buildMemberTreeHtml($node['subDept']);
            }
            $treeHtmlStr .= '</ul></li>';
        }
        return $treeHtmlStr;
    }
//
//    public function leavelists() {
//        $model = $this->getModel('oa_application');
//        parent::lists($model);
//    }
//    public function overworklists(){
//        $this->display();
//    }
//
//    public function myworks(){
//        $this->display();
//    }
}